package com.sotnyk.sspeed.visual;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.sotnyk.sspeed.R;
import com.sotnyk.sspeed.utils.ITtsManager;
import com.sotnyk.sspeed.utils.SsAppState;


public class MainActivity extends SingleFragmentActivity
        implements ITtsManager, TextToSpeech.OnInitListener {

    private final static String TAG = "MainActivity";

    private TextToSpeech mTts;
    private Boolean isTtsInit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TTS initialising
        if (mTts == null)
            mTts = new TextToSpeech(this, this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //Close the Text to Speech Library
        if (mTts != null) {
            mTts.stop();
            mTts.shutdown();
            mTts = null;
            isTtsInit = false;
            Log.d(TAG, "TTS Destroyed");
        }
    }

    @Override
    protected Fragment createFragment() {
        return new MainSSpeedFragment();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
    }

    // This method is called once the menu is selected
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                // Launch settings activity
                Intent i = new Intent(this, SettingsActivity.class);
                startActivity(i);
                break;
            case R.id.toggleTheme:
                SsAppState state = SsAppState.get(getApplicationContext());
                state.setDarkThemeUsed(!state.getDarkThemeUsed());
                this.recreate();
                return true;
        }

        return true;
    }

    @Override
    public void onInit(int status) {
        isTtsInit = status == TextToSpeech.SUCCESS;
        Log.d(TAG, "TTS initialized with status " + status);
    }

    @TargetApi(14)
    public void speakIfSilence(String text) {
        if (!isTtsInit)
            return;
        if (mTts.isSpeaking())
            return;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mTts.speak(text, TextToSpeech.QUEUE_ADD, Bundle.EMPTY, TAG + System.currentTimeMillis());
        } else {
            //noinspection deprecation
            mTts.speak(text, TextToSpeech.QUEUE_ADD, null);
        }
    }
}
